require(['loading'], function(loading) {
	//获取url中的id参数
	var params = getUrlParams();
	var goodsId = params.goodsId ? params.goodsId : '';
	var page, units, totalSupply, rangeBegin;
	window.onpopstate = function(event) {
		if(page == 2) {
			//			history.back();
			window.location.href = self_base_path + "/sales/wholesale_management.html";
		} else {
			$('section').animate({
				'bottom': '-100%'
			});
			$('#content').show();
		}
	};

	//日期控件实例化
	var calendar = window.components.calendar;
	var time2 = '145670988876';
	var timePicker = new Vue({
		el: '#target',
		data: {
			time: time2
		},
		methods: {
			setPickerTime: function(t) {
				this.data.time = t
			}
		},
		components: {
			'vue-calendar': calendar
		}
	});
	Vue.http.options.emulateJSON = true;
	var publishGoods = new Vue({
		el: '#publishGoods',
		data: {
			goodsDetails: [],
			mainImage: [],
			mainImageStr: [],
			detailsPics: [],
			detailsPicsStr: [],
			classData: [],
			unitsData: [],
			showLoading: false,
			goodsDetailsUrl: wxUrl + '/v3.3/goods/goodsDetails',
			publishGoodsUrl: wxUrl + '/v3.3/goods/publishGoods',
			classUrl: wxUrl + '/v3.3/tbuyingInfo/findSonGoodsClass',
			unitsUrl: wxUrl + '/v3.3/goods/getUnits',
			goodsDetailsItem: {
				params: {
					token: token,
					userToken: userToken,
					goodsId: goodsId
				}
			},
			publishGoodsItem: {
				token: token,
				userToken: userToken,
				goodsName: '',
				mainImage: '',
				goodsClassId: '',
				totalSupply: 0,
				rangeBegin: 0,
				price: 0,
				unit: '',
				detailsDesc: '',
				detailsPics: '',
				freightCharge: 1,
				goodsId: '',
				supplyTimeBegin: '',
				supplyTimeEnd: ''
			},
			classItem: {
				params: {
					token: token,
					userToken: userToken,
					parentId: ''
				}
			},
			unitsItem: {
				params: {
					token: token,
					userToken: userToken
				}
			}
		},
		ready: function() {
			if(goodsId != null && goodsId != '') {
				this.goodsDetailsItem.params.goodsId = goodsId;
				this.getGoodsDetails();
			}
			this.getUnits();
		},
		methods: {
			getGoodsDetails: function() {
				this.$http.get(this.goodsDetailsUrl, this.goodsDetailsItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						var goodsData = result.data.goods;
						this.$set('goodsDetails', goodsData);
						$("#productTitle span").text(goodsData.goodsName.length + "/30");
						$("#productDetail span").text(goodsData.detailsDesc.length + "/800");
						for(var i in goodsData.mainImage) {
							this.mainImage.push(goodsData.mainImage[i].pic);
							this.mainImageStr.push(goodsData.mainImage[i].picName);
						}
						for(var i in goodsData.detailsPics) {
							this.detailsPics.push(goodsData.detailsPics[i].pic);
							this.detailsPicsStr.push(goodsData.detailsPics[i].picName);
						}
						detail_len = goodsData.detailsPics.length;
						$('#detailImgLen').text(detail_len);
						
						if(goodsData.mainImage.length == 6) {
							$('#uploadMainImgBtn').hide();
						}
						if(goodsData.detailsPics.length == 9) {
							$('#uploadDetailImgBtn').hide();
						}
						
						$('#_totalSupply').val(goodsData.totalSupply + goodsData.unit);
						$('#_beginPrice').val(goodsData.rangeBegin + goodsData.unit + '起批，' + goodsData.price + '元/' + goodsData.unit);
						units = goodsData.unit;
						$('#detailsText').text('已填写');
						$('#supplyTimeBegin').val(goodsData.supplyTimeBegin);
						$('#supplyTimeEnd').val(goodsData.supplyTimeEnd);
						setTimeout(function() {
							$('#showTimes').val(goodsData.supplyTimeBegin + ' - ' + goodsData.supplyTimeEnd);
						}, 100);
						var freightCharge = goodsData.freightCharge;
						$('.yunfei').eq(freightCharge - 1).prop('checked', 'checked');

					}, function(response) {
						//errorCallback
					});
			},
			publishGoods: function() {
				if(goodsId != null && goodsId != '') {
					this.publishGoodsItem.goodsId = goodsId;
				}
				//验证商品标题
				var goodsName = $('#TextArea1').val();
				if(goodsName.length == 0) {
					promptBox("请输入商品标题！");
					return;
				}
				//验证商品主图
				var mainImgLen = this.mainImageStr.length;
				if(mainImgLen == 0) {
					promptBox("请上传商品主图！");
					return;
				}
				//验证商品分类
				var goodsClassId = $('#goodsClassId').val();
				if(goodsClassId.length == 0) {
					promptBox("请选择商品分类！");
					return;
				}
				//验证总供应量
				totalSupply = $('#totalSupply').val();
				if(totalSupply.length == 0) {
					promptBox("请输入总供应量！");
					return;
				}
				//验证总量单位
				var unit = $('#supplyUnite .unitTxt').val();
				if(unit.length == 0) {
					promptBox("请选择总量单位！");
					return;
				}
				//验证起批量
				rangeBegin = $('#rangeBegin').val();
				if(rangeBegin.length == 0) {
					promptBox("请输入起批量！");
					return;
				}
				//验证价格单位
				var price = $('#price').val();
				//验证上市时间
				var supplyTimeBegin = $('#supplyTimeBegin').val();
				if(supplyTimeBegin.length == 0) {
					promptBox("请选择上市时间！");
					return;
				}
				//验证下市时间
				var supplyTimeEnd = $('#supplyTimeEnd').val();
				if(supplyTimeEnd.length == 0) {
					promptBox("请选择下市时间！");
					return;
				}
				//验证商品详情描述
				var detailsDesc = $('#TextArea2').val();
				if(detailsDesc.length == 0) {
					promptBox("请输入商品详情描述！");
					return;
				}
				//验证商品详情图片
				var detailsImgLen = this.detailsPicsStr.length;
				if(detailsImgLen == 0) {
					promptBox("请上传商品详情图片！");
					return;
				}
				//验证运费
				var freightCharge = $('input:checked').val();
				if(freightCharge == undefined || freightCharge == '' || freightCharge == null) {
					promptBox("请选择运费方式！");
					return;
				}

				this.publishGoodsItem.goodsName = goodsName;
				this.publishGoodsItem.mainImage = this.mainImageStr.join(',');
				this.publishGoodsItem.goodsClassId = goodsClassId;
				this.publishGoodsItem.totalSupply = totalSupply;
				this.publishGoodsItem.unit = unit;
				this.publishGoodsItem.rangeBegin = rangeBegin;
				this.publishGoodsItem.price = price;
				this.publishGoodsItem.supplyTimeBegin = supplyTimeBegin;
				this.publishGoodsItem.supplyTimeEnd = supplyTimeEnd;
				this.publishGoodsItem.detailsDesc = detailsDesc;
				this.publishGoodsItem.detailsPics = this.detailsPicsStr.join(',');
				this.publishGoodsItem.freightCharge = freightCharge;
				this.$http.post(this.publishGoodsUrl, this.publishGoodsItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						if(result.code == 0) {
							window.location.href = self_base_path + "/sales/releaseSuccess.html?classId=" + goodsClassId;
						}
					}, function(response) {
						//errorCallback
					});
			},
			getClassData: function(e) {
				//获取顶级分类
				this.$http.get(this.classUrl, this.classItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						var classData = result.data.result;
						this.$set('classData', classData);
						$("#classBox").scrollTop(0);
					}, function(response) {

					});
			},
			getChildClass: function(e) {
				var dId = $(e.currentTarget).attr('id');
				this.classItem.params.parentId = dId;
				var dText = $(e.currentTarget).text();
				if(typeof($(e.currentTarget).attr('data-id')) != "undefined") {
					this.islowest = true; //判断已经是最底层
				}
				$("#classBox").scrollTop(0);
				//获取子类
				this.$http.get(this.classUrl, this.classItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						var classData = result.data.result;
						this.$set('classData', classData);
						if(this.islowest) {
							$("#content").show();
							$("#goodsClassName").val(dText);
							$("#goodsClassId").val(dId);
							$("#areaLayer").animate({
								"bottom": "-100%"
							});
							this.islowest = false;
							this.classItem.params.parentId = '';
						}
					}, function(response) {

					});
			},
			getUnits: function() {
				//获取单位
				this.$http.get(this.unitsUrl, this.unitsItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('unitsData', result.data.units);
					}, function(response) {
						//errorCallback
					});
			}

		}
	});

	//上传主图 6张
	$('#uploadMainImgBtn').diyUpload({
		url: wxUrl + '/v3.3/personalInfo/upload',
		success: function(data) {
			if(data.data.success) {
				if(publishGoods.mainImageStr.length < 6){
					publishGoods.mainImage.push(data.data.fullurl);
					publishGoods.mainImageStr.push(data.data.url);
				}
				if(publishGoods.mainImageStr.length == 6) {
					$('#uploadMainImgBtn').hide();
				}
			} else {
				promptBox('上传失败！');
			}
		},
		error: function(err) {
			promptBox(err);
		}
	});
	//上传详情图9张
	$('#uploadDetailImgBtn').detUpload({
		url: wxUrl + '/v3.3/personalInfo/upload',
		success: function(data) {
			if(data.data.success) {
				if(publishGoods.detailsPicsStr.length < 9){
					publishGoods.detailsPics.push(data.data.fullurl);
					publishGoods.detailsPicsStr.push(data.data.url);
				}
				if(publishGoods.detailsPicsStr.length == 9) {
					$('#uploadDetailImgBtn').hide();
				}
				$('#detailImgLen').text(publishGoods.detailsPicsStr.length);
			} else {
				promptBox('上传失败！');
			}
		},
		error: function(err) {
			promptBox(err);
		}
	});

	$(function() {
		//删除主图的图片
		$('#sdd_uploads').on('click', '.clearpic', function() {
			var  index  =  $('#sdd_uploads li').index($(this).closest('#sdd_uploads li'));
			publishGoods.mainImage.splice(index, 1);
			publishGoods.mainImageStr.splice(index, 1);
			if(publishGoods.mainImageStr.length < 6) {
				$('#uploadMainImgBtn').show();
			}
		});

		//删除详情的图片
		$('#sdd_upDetail').on('click', '.clearpic', function() {
			var  index  =  $('#sdd_upDetail li').index($(this).closest('#sdd_upDetail li'));
			publishGoods.detailsPics.splice(index, 1);
			publishGoods.detailsPicsStr.splice(index, 1);
			if(publishGoods.detailsPicsStr.length < 9) {
				$('#uploadDetailImgBtn').show();
			}
			$('#detailImgLen').text(publishGoods.detailsPicsStr.length);
		});

		//TextArea字数规则限制
		var nums;

		function words_deal(obj, nums) {
			var curLength = $(obj).val().length;
			if(curLength > nums) {
				var num = $(obj).val().substr(0, nums);
				$(obj).siblings("span").text(nums + "/" + nums);
				$(obj).val(num);
				promptBox("输入内容字数超过限制！");
			} else {
				$(obj).siblings("span").text($(obj).val().length + "/" + nums);
			}
			TextAreas = $(obj).val();
		}
		$("#TextArea1").on('input propertychange', function() {
			nums = 30;
			words_deal(this, nums);
		});
		$("#TextArea2").on('input propertychange', function() {
			nums = 800;
			words_deal(this, nums);
		});

		//关闭弹层
		function closeMod() {
			page = 2;
			$("#content").show();
			$("section").animate({
				"bottom": "-100%"
			});
		}

		//选择种类弹层
		$("#goodsClass").click(function() { //打开种类
			publishGoods.getClassData();
			$("#areaLayer").animate({
				"bottom": 0
			});
			history.pushState({}, null, "");
			page = 1;
			$("#content").hide();
		});
		$("#areaLayer header").click(function() { //关闭种类
			closeMod();
		});

		//总供应量弹层
		$("#totalSupply_s").click(function() { //打开总量
			$("#areaLayer1").animate({
				"bottom": 0
			});
			history.pushState({}, null, "");
			page = 1;
			$("#content").hide();
		});
		$("#areaLayer1 header").click(function() { //关闭总量
			closeMod();
		});
		$("#wholesaleSave").click(function() { //保存总量按钮
			totalSupply = parseInt($('#totalSupply').val());
			units = $('#supplyUnite .unitTxt').val();
			if(totalSupply == null || totalSupply == '') {
				promptBox("请输入供应总量！");
				return;
			} else {
				var re = /^[1-9]\d{0,9}$$/; //正整数-正则表达式/^\d+(\.\d{1,2})?$/
				if(!re.test(totalSupply)) {
					promptBox("供应总量必须为1-999999999的正整数！");
					return;
				}
			}
			if(units == null || units == '') {
				promptBox("请选择单位！");
				return;
			}
			$('#_totalSupply').val(totalSupply + units);
			if(goodsId != null && goodsId != ''){
				$('#_beginPrice').val(publishGoods.goodsDetails.rangeBegin + units + '起批，' + publishGoods.goodsDetails.price + '元/' + units);
			}
			closeMod();
		});

		//起批量,单价弹层
		$("#wholesale").click(function() { //打开起批量
			var _totalSupply = $('#_totalSupply').val();
			console.log(_totalSupply);
			if(_totalSupply == undefined || _totalSupply == '') {
				promptBox("请先输入总供应量信息！");
				return;
			}
			$("#areaLayer2").animate({
				"bottom": 0
			});
			history.pushState({}, null, "");
			page = 1;
			$("#content").hide();
		});
		$("#areaLayer2 header").click(function() { //关闭起批量
			closeMod();
		});
		$("#supplySave").click(function() { //起批量保存
			rangeBegin = $('#rangeBegin').val();
			var price = $('#price').val();
			if(rangeBegin == null || rangeBegin == '') {
				promptBox("请输入起批量！");
				return;
			}else if(parseInt(rangeBegin) > parseInt(totalSupply)) {
				promptBox("起批量不能大于供应总量！");
				return;
			}else {
				var re = /^[1-9]\d{0,7}$$/; //正整数-正则表达式
				if(!re.test(rangeBegin) || rangeBegin > 9000000) {
					promptBox("起批量必须为1-9000000的正整数！");
					return;
				}
			}
			if(price == null || price == '') {
				var beginPrice = rangeBegin + units + '起批,可议';
			} else {
				var re = /^([1-9]\d{1,7}|\d)(\.\d\d)?$/; //正则 保留两位小数
				if(!re.test(price) || price > 9000000 || price == 0) {
					promptBox("单价必须为0.01-9000000的正数！");
					return;
				}
				var beginPrice = rangeBegin + units + '起批, ' + price + '元' + '/' + units;
			}
			$('#_beginPrice').val(beginPrice);
			closeMod();
		});


		//图文详情弹层
		$("#proDetails").click(function() { //打开图文详情
			$("#areaLayer3").animate({
				"bottom": 0
			});
			history.pushState({}, null, "");
			page = 1;
			$("#content").hide();
		});
		$("#areaLayer3 header").click(function() { //关闭图文详情
			closeMod();
		});
		$("#detailsSave").click(function() { //图文详情保存
			var detailsDesc = $('#TextArea2').val();
			var detailImgLen = publishGoods.detailsPicsStr.length;
			if(detailsDesc == null || detailsDesc == '') {
				promptBox("请输入商品的详情描述！");
				return;
			} else {
				var len = detailsDesc.length;
				if(len > 800) {
					promptBox("最多可输入800个字！");
					return;
				}
			}
			if(detailImgLen == 0) {
				promptBox("请上传商品详情图！");
				return;
			}
			if(detailsDesc.length > 0 && detailImgLen > 0) {
				$("#detailsText").text("已填写");
			}
			closeMod();
		});

		//选择单位初始化
		setTimeout(function() {
			var curr = new Date().getFullYear();
			var opt = {
				'default': {
					theme: 'ios7',
					mode: 'scroller',
					animate: 'fade',
					defaultValue: 2
				},
				'select': {
					preset: 'select'
				}
			}
			$('.demo-test-select').scroller($.extend(opt['select'], opt['default']));
			if(publishGoods.goodsDetails.unit != undefined){
				$('#supplyUnite .unitTxt').val(publishGoods.goodsDetails.unit);
			}
		}, 800);
	});
});